<template>
  <Card title="编辑线索供应商">
    <SupplierTabsForm
      v-if="inited"
      type="clues"
      ref="supplier-form"
      :list="supplierInfoList"
      :data="supplierData" />
    <div class="actions">
      <el-button :loading="loading" :disabled="!inited" @click="handleSubmit()" type="primary">确认提交</el-button>
      <el-button :loading="loading" @click="handleBack()">取消</el-button>
    </div>
  </Card>
</template>
<script>
import SupplierTabsForm from '@/components/supplier/SupplierTabsForm';
import {
  updateCluesSupplier,
  getCluesSupplier,
} from '@/api/supplier/management/cluesSupplier';
import Dict from '@/mixins/supplier/dict';
import ManageArea from '@/mixins/supplier/manageArea';
import { getInitialFieldsValue, compactObj } from '@/pages/supplier/utils'
import {
  BUSINESS_INFORMATION_FIELDS,
  PRODUCT_INFORMATION_FIELDS,
  MANAGEMENT_INFORMATION_FIELDS,
  BILLING_INFORMATION_FIELDS,
} from './constants/info'

export default {
  mixins: [Dict, ManageArea],
  components: { SupplierTabsForm },
  data () {
    const { id = 0, processId = 0 } = this.$route.query
    const supplierBill = getInitialFieldsValue([
      BUSINESS_INFORMATION_FIELDS,
      PRODUCT_INFORMATION_FIELDS,
      MANAGEMENT_INFORMATION_FIELDS,
    ])
    const supplierContractBill = getInitialFieldsValue([
      BILLING_INFORMATION_FIELDS,
    ])
    supplierBill.supplierNatureClassify = 1
    supplierBill.businessContact = ''
    supplierBill.businessContactName = ''
    supplierBill.managementAreaName = ''
    supplierBill.mainCategoryCode = ''
    supplierBill.mainCategoryId = ''
    supplierBill.supplierClassify = 40899 // 线索
    supplierBill.purchaseStatus = supplierContractBill.purchaseStatus
    supplierBill.stopPurchaseReason = supplierContractBill.stopPurchaseReason
    supplierBill.lastYearPurchaseAmount = supplierContractBill.lastYearPurchaseAmount
    supplierBill.yearPurchaseAmount = supplierContractBill.yearPurchaseAmount
    supplierBill.purchaseAddRatio = supplierContractBill.purchaseAddRatio
    supplierContractBill.warrantyPeriodStandard = supplierBill.warrantyPeriodStandard
    supplierContractBill.warrantyPeriod = supplierBill.warrantyPeriod
    supplierContractBill.qualityCompensation = supplierBill.qualityCompensation
    supplierContractBill.salesSupport = supplierBill.salesSupport
    supplierContractBill.signContract = supplierBill.signContract
    const supplierCooperationAreaBillList = []
    const supplierCooperativeBrandList = []
    const supplierManageCategoryBillList = []
    const supplierPersonBillList = []
    return {
      id,
      processId,
      inited: false,
      loading: false,
      supplierInfoList: [{
        name: '基本信息',
        children: [{
          name: '工商信息',
          ref: 'business-information-form',
          formFields: BUSINESS_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
          qixinbao: true,
          showMessage: false,
        }, {
          name: '启信宝信息',
          ref: 'qxb-information-form',
          type: 'qxbInfo',
          dataSource: 'supplierBill',
        }]
      }, {
        name: '人员信息',
        children: [{
          ref: 'supplier-staff-list',
          type: 'staffList',
          dataSource: ['supplierPersonBillList'],
        }]
      }, {
        name: '商品信息',
        children: [{
          name: '商品信息',
          ref: 'product-information-form',
          formFields: PRODUCT_INFORMATION_FIELDS,
          dataSource: 'supplierBill',
        }],
      }, {
        name: '管理信息',
        children: [{
          name: '管理信息',
          ref: 'management-information-form',
          formFields: MANAGEMENT_INFORMATION_FIELDS.filter(item => {
            return !['supplierCode', 'createUser', 'createTime'].includes(item.prop)
          }),
          dataSource: 'supplierBill',
        }],
      }, {
        name: '合同信息',
        children: [ {
          name: '结算信息',
          ref: 'billing-information-form',
          formFields: BILLING_INFORMATION_FIELDS,
          dataSource: 'supplierContractBill',
        }],
      }, {
        name: '变更记录',
        type: 'changeRecord',
        id
      }],
      supplierData: {
        supplierBill,
        supplierContractBill,
        supplierCooperationAreaBillList,
        supplierCooperativeBrandList,
        supplierManageCategoryBillList,
        supplierPersonBillList,
      }
    }
  },
  created () {
    const { id } = this.$route.query
    if (id) {
      this.initSupplierData(id)
    } else {
      this.handleBack()
    }
  },
  methods: {
    // 获取供应商数据
    async initSupplierData (supplierId) {
      const { status, result = [] } = await getCluesSupplier({ supplierId })
      if (status === '0' && result) {
        this.setData({
          supplierBill: result.cluesSupplier,
          supplierContractBill: result.cluesSupplierContract,
          supplierPersonBillList: result.cluesSupplierPersonList,
          supplierManageCategoryBillList: result.cluesSupplierManageCategoryList,
        })
        this.inited = true
      }
    },
    // 初始化表单数据
    setData (data) {
      data = compactObj(data, this.supplierData)
      const {
        supplierBill,
        supplierManageCategoryBillList,
      } = data

      if (supplierBill && supplierBill.businessTerm) {
        const [businessTermStart = '', businessTermEnd = ''] = supplierBill.businessTerm.split(',')
        supplierBill.businessTermStart = businessTermStart
        supplierBill.businessTermEnd = businessTermEnd
      }

      // 经营品类
      if (supplierManageCategoryBillList && supplierManageCategoryBillList.length) {
        data.supplierBill.manageCategory = supplierManageCategoryBillList.map((item) => {
          return {
            categoryName: item.manageCategory,
            categoryNo: item.manageCategoryCode,
            categoryUuid: item.manageCategoryId,
          }
        })
      } else {
        data.supplierBill.manageCategory = []
      }

      for (let [k, v] of Object.entries(data)) {
        if (Array.isArray(v)) {
          if (v.length) {
            this.supplierData[k] = v
          }
        } else if (v) {
          this.supplierData[k] = v
        }
      }
    },
    // 提交
    handleSubmit () {
      this.$refs['supplier-form'].getData(1).then((data) => {
        if (data) {
          this.editSupplierDetail({
            cluesSupplier: data.supplierBill,
            cluesSupplierContract: data.supplierContractBill,
            cluesSupplierPersonList: data.supplierPersonBillList,
            cluesSupplierManageCategoryList: data.supplierManageCategoryBillList,
          }).catch((reason) => {
            console.log('reason', reason)
            this.loading = false
          })
        }
      })
    },
    // 编辑供应商
    async editSupplierDetail (data) {
      this.loading = true
      const resp = await updateCluesSupplier(data)
      this.loading = false
      if (resp && resp.status === '0') {
        this.$message.success('保存成功')
        this.handleBack()
      }
    },
    handleBack () {
      this.$router.go(-1)
    }
  },
}
</script>
